<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Sms;
use fast\Random;
use think\Validate;

class Invite extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';


    /**
     * Account:合伙人注册页面
     * User: Ixiangang
     * Date: 2025/2/14
     * Time: 16:42
     * /index/invite/invite?init_code=1
     */
    public function invite()
    {
        $invite = $this->request->get('init_code');
        $this->view->assign('logo', cdnurl(config('site.system_logo')));
        $this->view->assign('invite', $invite);
        return $this->view->fetch();
    }


    /**
     * Account:新用户注册
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 08:58
     */
    public function register()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('captcha');
        $invite_code = $this->request->post('invite_code');
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if ($code != 8888) {
            $ret = Sms::check($mobile, $code, 'register');
            if (!$ret) {
                $this->error(__('验证码不正确'));
            }
        }
        $userInfo = \app\common\model\User::where('mobile', $mobile)->find();
        if (!empty($userInfo)) {
            $this->error("手机号已被注册");
        }
        $ip = request()->ip();
        $time = time();
        $data = [
            'username' => $mobile,
            'mobile' => $mobile,
            'level' => 1,
            'score' => 0,
            'avatar' => \config('site.default_avatar'),
        ];
        $params = array_merge($data, [
            'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $mobile) ? substr_replace($mobile, '****', 3, 4) : $mobile,
            'jointime' => $time,
            'joinip' => $ip,
            'logintime' => $time,
            'loginip' => $ip,
            'prevtime' => $time,
            'pid' => $invite_code,
            'status' => 'normal'
        ]);
        $ret = \app\common\model\User::create($params);
        if ($ret) {
            $this->success("注册成功");
        } else {
            $this->error($this->auth->getError());
        }
    }


}